package org.rcy.framework.thrift.serializer;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolUtil;
import org.apache.thrift.protocol.TType;
import org.rcy.framework.thrift.metadata.FieldValueMetaData;

public class BasicSerializer implements Serializer {

	private static final String NULL_STRING = "NULL";

	@Override
	public Object read(TProtocol iprot, FieldValueMetaData valueMetaData) throws TException {
		byte type = valueMetaData.type;
		switch (type) {
		case TType.BOOL:
			return iprot.readBool();
		case TType.BYTE:
			return iprot.readByte();
		case TType.DOUBLE:
			return iprot.readDouble();
		case TType.I16:
			return iprot.readI16();
		case TType.I32:
			return iprot.readI32();
		case TType.I64:
			return iprot.readI64();
		case TType.STRING:
			String value = iprot.readString();
			return NULL_STRING.equals(value) ? null : value;
		default:
			TProtocolUtil.skip(iprot, type);
			return null;
		}
	}

	@Override
	public void write(TProtocol oprot, FieldValueMetaData valueMetaData, Object value) throws TException {
		boolean isNull = (value == null);
		byte type = valueMetaData.type;
		switch (type) {
		case TType.BOOL:
			oprot.writeBool((boolean) value);
			break;
		case TType.BYTE:
			oprot.writeByte((byte) value);
			break;
		case TType.DOUBLE:
			oprot.writeDouble((double) value);
			break;
		case TType.I16:
			oprot.writeI16((short) value);
			break;
		case TType.I32:
			oprot.writeI32((int) value);
			break;
		case TType.I64:
			oprot.writeI64((long) value);
			break;
		case TType.STRING:
			String str = isNull ? NULL_STRING : (String) value;
			oprot.writeString(str);
			break;

		default:
			break;
		}

	}
}
